import { useSnapshot } from 'valtio'
import { Icon } from '@taroify/icons'
import { useBoolean, useReactive } from 'ahooks'
import { useMemo, useRef, useState } from 'react'
import { type FormInstance } from '@taroify/core/form'
import { Text, Textarea, View } from '@tarojs/components'
import { Button, Cell, Field, Form, Image, Input, Tag } from '@taroify/core'

import { listCars } from '@/apis/car'
import { listAddrs } from '@/apis/addr'
import { derivedState } from '@/stores'
import { useStorage } from '@/hooks/useStorage'
import { useNavigate } from '@/hooks/useNavigate'
import TimeSelect from '@/components/TimeSelect'
import PopupSelect from '@/components/PopupSelect'
import { formatDay, formatMobile, formatTime, formatWeek } from '@/utils/format'

const renderCarBrief = ({ item, index }: { item: Data; index: number }) => (
  <View className="flex items-center gap-2 taroify-ellipsis" key={index}>
    <Text>
      {item.brand}
      {item.carType}
    </Text>
    <Text>
      {item.colour}
      {item.type}
    </Text>
  </View>
)

const renderCarLabel = ({ item, index }: { item: Data; index: number }) => (
  <View className="flex items-center gap-2" key={index}>
    <Text className="font-semibold">{item.carNumber}</Text>

    {item.isDefault === '1' && (
      <Tag className="ms-3 text-xs" color="primary" variant="outlined">
        默认
      </Tag>
    )}
  </View>
)

const renderAddrBrief = ({ item, index }: { item: Data; index: number }) => (
  <Text className="taroify-ellipsis" key={index}>
    {item.provinceName}
    {item.cityName}
    {item.countryName}
    {item.address}
  </Text>
)

const renderAddrLabel = ({ item, index }: { item: Data; index: number }) => (
  <View className="flex items-center gap-2" key={index}>
    <Text className="font-semibold">{item.contacts}</Text>
    <Text className="text-xs">{formatMobile(item.phone)}</Text>

    {item.isDefault === '1' && (
      <Tag className="ms-3 text-xs" color="primary" variant="outlined">
        默认
      </Tag>
    )}
  </View>
)

export default function Booking() {
  const form = useRef<FormInstance>()

  const state = useReactive({
    carId: '',
    addrId: '',
    mobile: '',
    contacts: '',
    timeStart: '',
    timeEnd: '',
    remark: '',
    paytype: 'wxpay',
  })
  const navigateTo = useNavigate()
  const [goods] = useStorage<Data>('goods')
  const { balance } = useSnapshot(derivedState)

  const [carShow, carActions] = useBoolean(false)
  const [addrShow, addrActions] = useBoolean(false)
  const [timeShow, timeActions] = useBoolean(false)
  const [couponShow, couponActions] = useBoolean(false)
  const [paytypeShow, paytypeActions] = useBoolean(false)

  const paytypes = useMemo(
    () => [
      {
        label: '微信支付',
        value: 'wxpay',
        icon: <Icon classPrefix="icon" name="wxpay" color="#07c160" size={20} />,
      },
      {
        label: '钱包支付',
        value: 'wallet',
        icon: <Icon classPrefix="icon" name="zhifu" color="var(--color-primary)" size={20} />,
        disabled: balance <= 0,
        extra: (
          <>
            <Text className="text-default">￥{balance}</Text>
            {balance <= 0 && <Text className="text-xs text-grey"> (余额不足)</Text>}
          </>
        ),
      },
    ],
    [balance]
  )

  const [car, setCar] = useState<Data>()
  const [addr, setAddr] = useState<Data>()
  // const [coupon, setCoupon] = useState<Data>()
  const [paytype, setPaytype] = useState<Data>(paytypes[0])

  const onSelectCar = (value: string, _: number, item: Data) => {
    state.carId = String(value)
    setCar(item)
  }

  const onSelectAddr = (value: string, _: number, item: Data) => {
    state.addrId = String(value)
    setAddr(item)
  }

  const onSelectTime = (value: string[]) => {
    state.timeStart = value[0]
    state.timeEnd = value[1]
  }

  const onSelectPaytype = (value: string, _: number, item: Data) => {
    state.paytype = String(value)
    setPaytype(item)
  }

  const handleSubmit = async () => {
    const vals = await form.current?.validate<Data>()
    console.log(vals)
  }

  return (
    <>
      <View className="page">
        <Form className="page-content py-4" ref={form} onSubmit={handleSubmit}>
          <Cell.Group className="!mb-4" inset>
            <Cell
              className="items-center gap-4 shadow-xl"
              icon={<Image width="48px" height="48px" src={goods?.smallPic} />}
              title={goods?.name}
              brief={`￥${goods?.price}`}
              briefClass="!text-base !text-error"
            />
          </Cell.Group>

          <Cell.Group className="!mb-3" inset style="--form-label-width:4em">
            <Field
              className="items-center gap-2"
              isLink
              name="carId"
              label="选择车辆"
              icon={<Icon classPrefix="icon" name="qiche1" color="var(--color-primary)" size={20} />}
              onClick={carActions.setTrue}
            >
              <View className="flex flex-col">
                {car ? (
                  <>
                    <Text className="text-sm">{car.carNumber}</Text>
                    <Text className="text-xs text-grey">
                      {car.brand}
                      {car.carType}
                      &nbsp;&nbsp;
                      {car.colour}
                      {car.type}
                    </Text>
                  </>
                ) : (
                  <Text className="text-sm text-placeholder">选择车辆</Text>
                )}
              </View>
            </Field>
          </Cell.Group>

          <Cell.Group className="!mb-3" inset style="--form-label-width:4em">
            <Field
              className="items-center gap-2"
              isLink
              name="addrId"
              label="选择地址"
              titleClass="max-w-20"
              icon={<Icon classPrefix="icon" name="weizhi" color="var(--color-primary)" size={20} />}
              onClick={addrActions.setTrue}
            >
              <View className="flex flex-col">
                {addr ? (
                  <>
                    <Text className="text-sm">
                      {addr.contacts} {formatMobile(addr.phone)}
                    </Text>
                    <Text className="text-xs text-grey">
                      {addr.provinceName}
                      {addr.cityName}
                      {addr.countryName}
                      {addr.address}
                    </Text>
                  </>
                ) : (
                  <Text className="text-sm text-placeholder">选择地址</Text>
                )}
              </View>
            </Field>
          </Cell.Group>

          <Cell.Group className="!mb-3" inset style="--form-label-width:4em">
            <Field
              className="items-center gap-2"
              name="contacts"
              label="车主姓名"
              icon={<Icon classPrefix="icon" name="wode" color="var(--color-primary)" size={20} />}
            >
              <Input placeholder="请输入车主姓名" />
            </Field>
            <Field
              className="items-center gap-2"
              name="mobile"
              label="联系电话"
              icon={<Icon classPrefix="icon" name="shouji" color="var(--color-primary)" size={20} />}
            >
              <Input type="number" placeholder="请输入联系电话" />
            </Field>
            <Field
              className="items-center gap-2"
              isLink
              name="time"
              label="预约时间"
              icon={<Icon classPrefix="icon" name="shijian" color="var(--color-primary)" size={20} />}
              onClick={timeActions.setTrue}
            >
              <View className="flex flex-col">
                {state.timeStart && state.timeEnd ? (
                  <>
                    <Text className="text-xs">
                      {formatDay(state.timeStart)} ({formatWeek(state.timeStart)})
                    </Text>
                    <Text className="text-xs">
                      {formatTime(state.timeStart)} - {formatTime(state.timeEnd)}
                    </Text>
                  </>
                ) : (
                  <Text className="text-sm text-placeholder">选择预约时间</Text>
                )}
              </View>
            </Field>
            <Field
              className="flex-wrap"
              name="remark"
              label="备注"
              titleClass="ps-2"
              valueClass="!flex-auto basis-full"
              icon={<Icon classPrefix="icon" name="beizhu" color="var(--color-primary)" size={20} />}
            >
              <Textarea className="p-2" placeholder="输入备注" style="width:600rpx;height:80rpx" />
            </Field>
          </Cell.Group>

          <Cell.Group className="!mb-3" inset>
            <Field
              className="items-center gap-2"
              isLink
              name="couponId"
              label="选择优惠券"
              icon={<Icon classPrefix="icon" name="youhuiquan" color="var(--color-primary)" size={16} />}
              onClick={couponActions.setTrue}
            >
              <Text className="flex-auto text-end">不使用优惠券</Text>
            </Field>
          </Cell.Group>

          <Cell.Group className="!mb-3" inset>
            <Field
              className="items-center gap-2"
              isLink
              name="paytype"
              label="选择支付方式"
              icon={<Icon classPrefix="icon" name="zhifufangshi" color="var(--color-primary)" size={20} />}
              onClick={paytypeActions.setTrue}
            >
              <View className="flex flex-auto items-center gap-2 justify-end">
                {paytype.icon}
                <Text>{paytype.label}</Text>
              </View>
            </Field>
          </Cell.Group>
        </Form>
      </View>

      <PopupSelect
        title="选择车辆"
        valueKey="id"
        open={carShow}
        emptyText="暂无车辆"
        request={listCars}
        renderLabel={renderCarLabel}
        renderBrief={renderCarBrief}
        emptyExtra={
          <Button
            className="min-w-40"
            block
            color="primary"
            shape="round"
            onClick={() => navigateTo('/pages/car/edit')}
          >
            添加车辆
          </Button>
        }
        onClose={carActions.setFalse}
        onConfirm={onSelectCar}
      />

      <PopupSelect
        title="选择地址"
        valueKey="id"
        open={addrShow}
        emptyText="暂无地址"
        request={listAddrs}
        renderLabel={renderAddrLabel}
        renderBrief={renderAddrBrief}
        emptyExtra={
          <Button
            className="min-w-40"
            block
            color="primary"
            shape="round"
            onClick={() => navigateTo('/pages/address/edit')}
          >
            添加地址
          </Button>
        }
        onClose={addrActions.setFalse}
        onConfirm={onSelectAddr}
      />

      <TimeSelect open={timeShow} onClose={timeActions.setFalse} onConfirm={onSelectTime} />

      <PopupSelect open={couponShow} title="选择优惠券" emptyText="暂无优惠券" onClose={couponActions.setFalse} />

      <PopupSelect
        open={paytypeShow}
        data={paytypes}
        title="选择支付方式"
        renderItem={({ item, index, isSelected, onSelect }) => (
          <Cell
            key={index}
            className="gap-2"
            isLink
            align="center"
            icon={item.icon}
            title={item.label}
            children={item.extra}
            clickable={!item.disabled}
            rightIcon={isSelected ? <Icon name="checked" color="var(--color-primary)" size={24} /> : null}
            onClick={onSelect}
          />
        )}
        onClose={paytypeActions.setFalse}
        onConfirm={onSelectPaytype}
      />
    </>
  )
}
